package com.pai4j.ugc.service.ai;

import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.vo.response.moment.AiContent;
import com.pai4j.ugc.repository.dao.IMomentAiContentDAO;
import com.pai4j.ugc.repository.dao.IMomentAiKeywordDAO;
import com.pai4j.ugc.repository.entity.MomentAiContentEntity;
import com.pai4j.ugc.repository.entity.MomentAiKeywordEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 小型持久化服务：将 AI 内容分析结果与关键词索引在同一事务内落库
 */
@Service
public class AiContentPersistService {

    @Autowired
    private IMomentAiContentDAO momentAiContentDAO;

    @Autowired
    private IMomentAiKeywordDAO momentAiKeywordDAO;

    /**
     * 在同一事务中持久化 AI 分析内容并重建关键词倒排索引
     */
    @Transactional(rollbackFor = Exception.class)
    public void persistAiAnalysis(Long momentId, AiContent aiContent) {
        // 若 AI 内容为空，仅清理旧关键词，避免残留
        if (aiContent == null) {
            momentAiKeywordDAO.deleteByMomentId(momentId);
            return;
        }

        // 保存/更新 AI 内容
        MomentAiContentEntity entity = momentAiContentDAO.findByMomentId(momentId).orElse(new MomentAiContentEntity());
        entity.setMomentId(momentId);
        entity.setQualityScore(aiContent.getQualityScore());
        entity.setSentiment(aiContent.getSentiment());
        entity.setKeywords(JsonUtil.toJsonString(aiContent.getKeywords()));
        entity.setSummary(aiContent.getSummary());
        momentAiContentDAO.save(entity);

        // 重建关键词倒排索引
        momentAiKeywordDAO.deleteByMomentId(momentId);
        if (aiContent.getKeywords() != null) {
            for (String kw : aiContent.getKeywords()) {
                if (StringUtils.isNotBlank(kw)) {
                    MomentAiKeywordEntity e = new MomentAiKeywordEntity();
                    e.setMomentId(momentId);
                    e.setKeyword(kw.trim());
                    momentAiKeywordDAO.save(e);
                }
            }
        }
    }
}

